package com.czz.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.czz.common.exception.CustomerException;
import com.czz.common.exception.ResultCodeEnum;
import com.czz.oss.service.FileUploadService;
import com.czz.oss.utils.ConstantPropertiesUtil;
import com.czz.oss.utils.NumberUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @ClassName: FileServiceImpl
 * @Author Czz
 * @Date 2020/1/21
 * @Time 15:33
 **/
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Override
    public Map uploadFile(MultipartFile file, String courseId) {

        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String fileHost = ConstantPropertiesUtil.FILE_HOST;

        //文件上传返回的url地址
        String uploadUrl = null;

        Map data = new HashMap();

        try {
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
            //OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)) {
                //创建bucket
                ossClient.createBucket(bucketName);
                //设置oss实例的访问权限：公共读
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }

            //获取上传文件流
            InputStream inputStream = file.getInputStream();

            //文件路径
            String filePath = null;

            String fileUrl = null;

            //如果为课时文档
            if (!StringUtils.isEmpty(courseId)){
                //建构文件路径：课程id/章节id
                filePath = courseId + "/" + NumberUtils.generateCode(6);
                //文件名：原始文件名
                fileUrl = fileHost + "/" + filePath + "/" + file.getOriginalFilename();
            }

            //其他上传文件
            else {
                //构建日期路径：avatar/2019/02/26/文件名
                filePath = new DateTime().toString("yyyy/MM/dd");
                //文件名：uuid.扩展名
                String original = file.getOriginalFilename();
                String fileName = UUID.randomUUID().toString();
                String fileType = original.substring(original.lastIndexOf("."));
                String newName = fileName + fileType;
                fileUrl = fileHost + "/" + filePath + "/" + newName;
            }

            //文件上传至阿里云
            ossClient.putObject(bucketName, fileUrl, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //获取url地址
            uploadUrl = "http://" + bucketName + "." + endPoint + "/" + fileUrl;

            data.put("url",uploadUrl);
            data.put("fileName", file.getOriginalFilename());

        } catch (IOException e) {
            throw new CustomerException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
        return data;
    }

    @Override
    public void deleteFile(String docUrl) {

        //将&&还原为/
        docUrl = docUrl.replaceAll("&&","/");

        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        //判断oss实例是否存在：如果不存在则创建，如果存在则获取
        //OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        if (!ossClient.doesBucketExist(bucketName)) {
            //创建bucket
            ossClient.createBucket(bucketName);
            //设置oss实例的访问权限：公共读
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }

        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(bucketName, docUrl);

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    @Override
    public void deleteFileBatch(List<String> files) {

        List<String> urlList = new ArrayList<>();

        //将&&还原为/
        for (int i = 0; i < files.size(); i++){
            String file = files.get(i).replaceAll("&&","/");
            urlList.add(file);
        }

        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        //判断oss实例是否存在：如果不存在则创建，如果存在则获取
        //OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        if (!ossClient.doesBucketExist(bucketName)) {
            //创建bucket
            ossClient.createBucket(bucketName);
            //设置oss实例的访问权限：公共读
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }

        //批量删除文件
        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(urlList));

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
